/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Articulo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author nan
 */
public class articulosListar implements ActionListener, KeyListener{

    private Conexion.ConexionBD conectar = new Conexion.ConexionBD();
    private articulosListarGUI ventana = new articulosListarGUI();
    private Articulo.MedGIngreso ingreso;
    private MedGModificar Mingreso ;
    private DefaultTableModel dtmArticulos;
    private Articulo.MedAgregarStock agStock;
    private Administracion.AdministracionMediador admin;

    public articulosListar(Administracion.AdministracionMediador a){
        ventana.setLocationRelativeTo(null);
        ventana.getjTextFieldCod().addKeyListener(new PresionarTecla());
        admin = a;
        ventana.setActionListeners(this);
        ventana.setKeyListener(this);
        ventana.setVisible(true);
        actualizarTabla();
    }

    public void actualizarTabla(){
        String[] titulos = {"Cod", "Nombre", "Marca", "Descrip", "$ Costo", "Stock Min", "Stock Max", "Stock"};
        Object[][] datos = {};
        dtmArticulos = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Articulo\"";
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString("codArt"),
                rs.getString("nombre"),
                rs.getString("marca"),
                rs.getString("descripcion"),
                rs.getDouble("precioCosto"),
                rs.getInt("StockMin"),
                rs.getInt("StockMax"),
                rs.getInt("Stock")};
                dtmArticulos.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        ventana.getjTableArticulos().setModel(dtmArticulos);
    }

    public void actualizarPorCampo(String nombre,String cod){
        String[] titulos = {"Cod", "Nombre", "Marca", "Descrip", "$ Costo", "Stock Min", "Stock Max", "Stock"};
        Object[][] datos = {};
        dtmArticulos = new DefaultTableModel(datos, titulos);

        conectar.conectar();
        Statement st;
        try {
            st = conectar.getConn().createStatement();
            String consulta = "SELECT * FROM \"Articulo\" WHERE nombre='"+nombre+"' OR \"codArt\" = '"+cod+"';" ;
            ResultSet rs = st.executeQuery(consulta);
            String id = null;
            while (rs.next()){
                Object[] fila = {rs.getString("codArt"),
                rs.getString("nombre"),
                rs.getString("marca"),
                rs.getString("descripcion"),
                rs.getDouble("precioCosto"),
                rs.getInt("StockMin"),
                rs.getInt("StockMax"),
                rs.getInt("Stock")};
                dtmArticulos.addRow(fila);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        ventana.getjTableArticulos().setModel(dtmArticulos);
        conectar.cerrar();
    }

    public void actionPerformed(ActionEvent e) {
        int select = ventana.getjTableArticulos().getSelectedRow();
        if (e.getSource() == ventana.getjButtonAgregar()){
            agregar();
        } else if (e.getSource() == ventana.getjButtonMostrarTodos()){
            actualizarTabla();
            ventana.getjTextFieldCod().setText("");
            ventana.getjTextFieldNombre().setText("");
        } else if (e.getSource() == ventana.getjButtonEliminar()){
            eliminar(select);
            admin.ActualizarConStocMin();
        } else if (e.getSource() == ventana.getjButtonModificar()){
            modificar(select);
        } if (e.getSource() == ventana.getjButtonMostrarCampo()){
            String cod = ventana.getjTextFieldCod().getText();
            String nombre =ventana.getjTextFieldNombre().getText();
            actualizarPorCampo(nombre,cod);
            ventana.getjTextFieldCod().setText("");
            ventana.getjTextFieldNombre().setText("");
        }
        if (e.getSource() == ventana.getjButtonAgregarStock()){
            agregarStock(select);
        }
        if (e.getSource() == ventana.getjButtonSalir()){
            ventana.dispose();
            admin.ActualizarConStocMin();
        }

        
    }

    private void agregarStock(int select){
        if (select != -1){
            //
            if (this.agStock == null){
                agStock = new Articulo.MedAgregarStock(this);
                System.out.println(ventana.getjTableArticulos().getValueAt(select, 0).toString());
                agStock.buscar(ventana.getjTableArticulos().getValueAt(select, 0).toString());
                agStock.setVisible(true);
                //agStock.setArticulo(idArticulo);
            } else {
                //agStock.setArticulo(idArticulo);
                System.out.println(ventana.getjTableArticulos().getValueAt(select, 0).toString());
                agStock.buscar(ventana.getjTableArticulos().getValueAt(select, 0).toString());
                agStock.setVisible(true);
            }
            admin.ActualizarConStocMin();
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }

    }

    private void agregar(){
        if (this.ingreso == null){
            ingreso = new Articulo.MedGIngreso(this);
        } else {
            ingreso.setVisible(true);
        }
        admin.ActualizarConStocMin();
    }

    private void modificar(int select){
        if (select != -1){
            if (this.Mingreso == null){
                Mingreso = new MedGModificar(this);
                Mingreso.setClave(dtmArticulos.getValueAt(select, 0).toString());
                Mingreso.getIngreso().getjTextFieldNombre().setText(dtmArticulos.getValueAt(select, 1).toString());
                Mingreso.getIngreso().getjTextFieldmarca().setText(dtmArticulos.getValueAt(select, 2).toString());
                Mingreso.getIngreso().getjTextFielddescripcion().setText(dtmArticulos.getValueAt(select, 3).toString());
                Mingreso.getIngreso().getjTextFieldprecioCosto().setText(dtmArticulos.getValueAt(select, 4).toString());
                Mingreso.getIngreso().getjTextFieldStockMin().setText(dtmArticulos.getValueAt(select, 5).toString());
                Mingreso.getIngreso().getjTextFieldStockMax().setText(dtmArticulos.getValueAt(select, 6).toString());
                Mingreso.getIngreso().getStock().setText(dtmArticulos.getValueAt(select, 7).toString());
            } else {
                Mingreso.setClave(dtmArticulos.getValueAt(select, 0).toString());
                Mingreso.getIngreso().getjTextFieldNombre().setText(dtmArticulos.getValueAt(select, 1).toString());
                Mingreso.getIngreso().getjTextFieldmarca().setText(dtmArticulos.getValueAt(select, 2).toString());
                Mingreso.getIngreso().getjTextFielddescripcion().setText(dtmArticulos.getValueAt(select, 3).toString());
                Mingreso.getIngreso().getjTextFieldprecioCosto().setText(dtmArticulos.getValueAt(select, 4).toString());
                Mingreso.getIngreso().getjTextFieldStockMin().setText(dtmArticulos.getValueAt(select, 5).toString());
                Mingreso.getIngreso().getjTextFieldStockMax().setText(dtmArticulos.getValueAt(select, 6).toString());
                Mingreso.getIngreso().getStock().setText(dtmArticulos.getValueAt(select, 7).toString());
                Mingreso.setVisible(true);
            }
            admin.ActualizarConStocMin();
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void eliminar(int select){
        if (select != -1){
            String a = dtmArticulos.getValueAt(select, 0).toString();

            conectar.conectar();
            int confirmado = JOptionPane.showConfirmDialog(null,"¿Está seguro que desea eliminar el articulo?", "Eliminar Articulo", JOptionPane.YES_NO_OPTION);

            if (JOptionPane.OK_OPTION == confirmado){
                try {
                    Statement st = conectar.getConn().createStatement();
                    System.out.println(a);
                    String borrar = "DELETE FROM \"Articulo\" WHERE \"codArt\" = '"+a+"';";
                    System.out.println(st.execute(borrar));
                    st.close();
                } catch (Exception ex) {

                    ex.printStackTrace();
                }
                conectar.cerrar();
                this.actualizarTabla();
                JOptionPane.showMessageDialog(null, "Se ha eliminado el Articulo", "Elemento eliminado", JOptionPane.INFORMATION_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe seleccionar un elemento", "Error por seleccion nula", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void keyTyped(KeyEvent e) {
        if (e.getSource()== ventana.getjTextFieldCod()){
            char caracter = e.getKeyChar();
            if((caracter == '$')){
                e.consume();
            }
        }

    }

    public void keyPressed(KeyEvent e) {   }

    public void keyReleased(KeyEvent e) {   }

    public void setVisible(boolean b) {
        ventana.setVisible(b);
    }




    public class PresionarTecla extends KeyAdapter {

      public void keyPressed(KeyEvent ke) {
          if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
              buscarCodigo(null);
          }
      }

        private void buscarCodigo(Object object) {
            String cod = ventana.getjTextFieldCod().getText();
            String nombre =ventana.getjTextFieldNombre().getText();
            actualizarPorCampo(nombre,cod);
            ventana.getjTextFieldCod().setText("");
            ventana.getjTextFieldNombre().setText("");
        }
    }
}
